package com.atguigu.flink.chapter06.state.keyed;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/*
键控状态：
    聚合状态
 */
public class AggregateStateDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        //输出每个传感器的平均水位
        env.socketTextStream("hadoop102",8888)
                .map(new WaterSensorMapFunction())
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private AggregatingState<WaterSensor, Double> avgVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        avgVcState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, Tuple2<Integer, Long>, Double>(
                                "avgVc",
                                new AggregateFunction<WaterSensor, Tuple2<Integer, Long>, Double>() {
                                    @Override
                                    public Tuple2<Integer, Long> createAccumulator() {
                                        return Tuple2.of(0, 0L);
                                    }

                                    @Override
                                    public Tuple2<Integer, Long> add(WaterSensor value,
                                                                     Tuple2<Integer, Long> acc) {
                                        return Tuple2.of(acc.f0 + value.getVc(), acc.f1 + 1);
                                    }

                                    @Override
                                    public Double getResult(Tuple2<Integer, Long> acc) {
                                        return acc.f0 * 1.0 / acc.f1;
                                    }

                                    @Override
                                    public Tuple2<Integer, Long> merge(Tuple2<Integer, Long> integerLongTuple2, Tuple2<Integer, Long> acc1) {
                                        return null;
                                    }
                                },
                                //Types.TUPLE(Types.INT,Types.LONG)
                                TypeInformation.of(new TypeHint<Tuple2<Integer, Long>>() {
                                })
                        ));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        avgVcState.add(value);

                        out.collect(ctx.getCurrentKey() + "的平均水位："  + avgVcState.get());
                    }
                })
                .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



//public class AggregateStateDemo {
//    public static void main(String[] args) {
//        Configuration conf = new Configuration();
//        conf.setInteger("rest.port",2000);
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
//        env.setParallelism(1);
//        //输出每个传感器的平均水位
//        env.socketTextStream("hadoop102",8888)
//                .map(new WaterSensorMapFunction())
//                .keyBy(WaterSensor::getId)
//                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
//
//                    private AggregatingState<WaterSensor, Double> avgVcState;
//
//                    @Override
//                    public void open(Configuration parameters) throws Exception {
//                        avgVcState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, Tuple2<Integer, Long>, Double>(
//                                "avgVc",
//                                new AggregateFunction<WaterSensor, Tuple2<Integer, Long>, Double>() {
//                                    @Override
//                                    public Tuple2<Integer, Long> createAccumulator() {
//                                        return Tuple2.of(0, 0L);
//                                    }
//
//                                    @Override
//                                    public Tuple2<Integer, Long> add(WaterSensor value,
//                                                                     Tuple2<Integer, Long> acc) {
//                                        return Tuple2.of(acc.f0 + value.getVc(), acc.f1 + 1);
//                                    }
//
//                                    @Override
//                                    public Double getResult(Tuple2<Integer, Long> acc) {
//                                        return acc.f0 * 1.0 / acc.f1;
//                                    }
//
//                                    @Override
//                                    public Tuple2<Integer, Long> merge(Tuple2<Integer, Long> integerLongTuple2,
//                                                                       Tuple2<Integer, Long> acc1) {
//                                        return null;
//                                    }
//                                },
//                                //Types.TUPLE(Types.INT,Types.LONG)
//                                TypeInformation.of(new TypeHint<Tuple2<Integer, Long>>() {
//                                })
//                        ));
//                    }
//
//                    @Override
//                    public void processElement(WaterSensor value,
//                                               Context ctx,
//                                               Collector<String> out) throws Exception {
//                        avgVcState.add(value);
//
//                        out.collect(ctx.getCurrentKey() + "的平均水位："  + avgVcState.get());
//                    }
//                })
//                .print();
//        try {
//            env.execute();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}


//public class AggregateStateDemo {
//    public static void main(String[] args) {
//        Configuration conf = new Configuration();
//        conf.setInteger("rest.port",2000);
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
//        env.setParallelism(1);
//        //输出每个传感器的平均水位
//        env.socketTextStream("hadoop102",8888)
//                .map(new WaterSensorMapFunction())
//                .keyBy(WaterSensor::getId)
//                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
//
//                    private AggregatingState<WaterSensor, Double> avgVcState;
//
//                    @Override
//                    public void open(Configuration parameters) throws Exception {
//                        avgVcState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, Tuple2<Integer, Long>, Double>(
//                                "avgVc",
//                                new AggregateFunction<WaterSensor, Tuple2<Integer, Long>, Double>() {
//                                    @Override
//                                    public Tuple2<Integer, Long> createAccumulator() {
//                                        return Tuple2.of(0, 0L);
//                                    }
//
//                                    @Override
//                                    public Tuple2<Integer, Long> add(WaterSensor value,
//                                                                     Tuple2<Integer, Long> acc) {
//                                        return Tuple2.of(acc.f0 + value.getVc(), acc.f1 + 1);
//                                    }
//
//                                    @Override
//                                    public Double getResult(Tuple2<Integer, Long> acc) {
//                                        return acc.f0 * 1.0 / acc.f1;
//                                    }
//
//                                    @Override
//                                    public Tuple2<Integer, Long> merge(Tuple2<Integer, Long> integerLongTuple2, Tuple2<Integer, Long> acc1) {
//                                        return null;
//                                    }
//                                },
//                                //Types.TUPLE(Types.INT,Types.LONG)
//                                TypeInformation.of(new TypeHint<Tuple2<Integer, Long>>() {
//                                })
//                        ));
//                    }
//
//                    @Override
//                    public void processElement(WaterSensor value,
//                                               Context ctx,
//                                               Collector<String> out) throws Exception {
//                            avgVcState.add(value);
//                            out.collect(ctx.getCurrentKey() + "的平均水位：" + avgVcState.get());
//                    }
//                })
//                .print();
//        try {
//            env.execute();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}